<template>
  <div class="db-bg">
    <div class="db-chat-window">
      <main class="db-chat-main" ref="chatMain">
        <div v-for="(msg, idx) in chatHistory" :key="idx" :class="['db-msg-row', msg.role]">
          <div class="db-msg-bubble">
            <div class="db-msg-content" v-html="renderMarkDown(msg.content)">
            </div>
          </div>
        </div>
        <div v-if="loading" class="db-msg-row ai">
          <div class="db-msg-bubble typing">AI正在输入...</div>
        </div>
      </main>
      <footer class="db-chat-footer">
        <textarea
          v-model="inputValue"
          @keydown.enter="onEnter"
          @keydown.shift.enter.stop
          placeholder="请输入内容，Shift+Enter换行"
        />
        <a-button
          type="primary"
          @click="sendMsg"
          :loading="loading"
          class="db-send-btn"
        >
          发送
        </a-button>
      </footer>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { useChatSessionsStore } from '@/stores/chatSessions'
import { marked } from 'marked'
marked.setOptions({
  gfm: true,  //支持Github风格
  breaks: true,
})

function renderMarkDown(content: string): string {
  if (!content) return ''
  return marked.parse(content)
}

const route = useRoute()
const chatStore = useChatSessionsStore()

// Refs
const inputValue = ref('')
const chatMain = ref<HTMLElement | null>(null)
const loading = ref(false)

// Computed
const currentSession = computed(() => chatStore.getActiveSession())
const chatHistory = computed(() => currentSession.value?.messages || [])

// 初始化聊天会话
onMounted(() => {
  initializeChatSession()
  console.log('----', chatStore.HomeQuery, route.query.q)
  console.log(chatStore.HomeQuery !== route.query.q)
  if (route.query.q && (chatStore.HomeQuery !== route.query.q)) {
    sendMessage(String(route.query.q))
    chatStore.HomeQuery = route.query.q
  }
  console.log(chatStore.HomeQuery !== route.query.q)
  scrollToBottom()
})

// 方法
function initializeChatSession() {
  if (chatStore.sessions.length === 0) {
    chatStore.createSession('新对话')
  }
}

function sendMessage(content: string) {
  if (!content.trim()) {
    // alert('消息不能为空')
    return
  }

  // 确保有活跃会话
  if (!currentSession.value) {
    chatStore.createSession('新对话')
  }

  // 添加用户消息
  chatStore.addMessage(chatStore.activeChatId, {
    role: 'user',
    content: content,
  })

  // 如果是第一条信息，把session标题改成这个信息
  console.log('--', chatStore.getActiveSession().messages.length)
  if (chatStore.getActiveSession().messages.length == 1) {
    chatStore.getActiveSession().title = content;
  }

  // 清空输入框（如果是手动发送）
  if (content === inputValue.value) {
    inputValue.value = ''
  }

  scrollToBottom()
  generateAIResponse(content)
}

function sendMsg() {
  sendMessage(inputValue.value.trim())
}

function generateAIResponse(userInput: string) {
  loading.value = true;
  const userInfo = JSON.parse(localStorage.getItem('userInfo'))
  chatStore.addMessage(chatStore.activeChatId,{
    role: 'ai',
    content: ''
  })
  const messages = chatStore.getActiveSession().messages
  fetch(import.meta.env.VITE_API_URL + 'chat/fluxChat', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      // 流式响应
      'Accept': 'text/event-stream',
    },
    body: JSON.stringify({
      message: userInput,
      chatId: chatStore.activeChatId,
      userId: userInfo.userId,
      chatName: '你好'
    })
  }).then(async (res) => {
    // console.log('res', res)
    if (!res.ok) {
      throw new Error('网络响应失败：' + res.statusText)
    }
    return res
  })
    .then(async (result: Response) => {
      if (!result.body) {
        throw new Error('响应体为空，无法读取数据流')
      }
      const reader = result.body.getReader()
      // console.log('reader', reader)
      const decoder = new TextDecoder()
      let buffer = ''
      // chatStore.addMessage(chatStore.activeChatId, message: { role: 'user' | 'ai', content: string });
      while (true) {
        const { done, value } = await reader.read()
        // console.log('value', value)
        if (done) {
          console.log('流结束')
          break
        }
        const chunk = decoder.decode(value)
        // console.log('chunk', chunk)
        buffer += chunk
        // console.log('buffer+', buffer)
        const lines = buffer.split('\n')
        buffer = lines.pop() || ''
        for (const line of lines) {
          // console.log('----line', line)
          if (line.startsWith('data:')) {
            messages[messages.length - 1].content += line.substring(5).replace(/\\n/g, '\n')
            scrollToBottomIfNearBottom()
          }
        }
      }
    })
  loading.value = false;
}

function scrollToBottom() {
  nextTick(() => {
    if (chatMain.value) {
      chatMain.value.scrollTop = chatMain.value.scrollHeight
    }
  })
}

function scrollToBottomIfNearBottom() {
  nextTick(() => {
    if (chatMain.value) {
      const container = chatMain.value
      const threshold = 100 // 距离底部多少像素以内才自动滚动
      const isNearBottom = container.scrollHeight - container.scrollTop - container.clientHeight < threshold
      if (isNearBottom) {
        chatMain.value.scrollTop = chatMain.value.scrollHeight
      }
    }
  })
}

function onEnter(e: KeyboardEvent) {
  if (e.shiftKey) return
  e.preventDefault()
  sendMsg()
}

defineExpose({scrollToBottom})
</script>

<style scoped>
/* 保持您原有的样式不变 */
.db-bg {
  background: #f5f6fa;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
.db-chat-window {
  width: 100%;
  max-width: 600px;
  background: #fff;
  border-radius: 20px;
  box-shadow: 0 8px 32px 0 rgba(53,120,229,0.08);
  display: flex;
  flex-direction: column;
  height: 85vh;
  min-height: 500px;
  margin: 32px auto;
}
.db-chat-main {
  flex: 1;
  overflow-y: auto;
  padding: 36px 32px 24px 32px;
  background: #f4f7fb;
  scrollbar-width: none;
  -ms-overflow-style: none;
}
.db-chat-main::-webkit-scrollbar {
  display: none;
}
.db-msg-row {
  display: flex;
  align-items: flex-end;
  margin-bottom: 18px;
}
.db-msg-row.user {
  flex-direction: row-reverse;
}
.db-msg-bubble {
  position: relative;
  max-width: 70%;
  border-radius: 18px;
  padding: 16px 22px;
  background: #fff;
  box-shadow: 0 1px 6px 0 rgba(53,120,229,0.04);
  margin: 0 auto;
  font-size: 16px;
}
.db-msg-row.user .db-msg-bubble {
  background: #3578e5;
  color: #fff;
  margin-right: 0;
  margin-left: auto;
}
.db-msg-row.ai .db-msg-bubble {
  background: #f0f4fa;
  color: #222;
  margin-left: 0;
  margin-right: auto;
}
.db-msg-row.user .db-msg-bubble::after {
  content: '';
  position: absolute;
  right: -8px;
  top: 16px;
  border-width: 8px 0 8px 8px;
  border-style: solid;
  border-color: transparent transparent transparent #3578e5;
}
.db-msg-row.ai .db-msg-bubble::after {
  content: '';
  position: absolute;
  left: -8px;
  top: 16px;
  border-width: 8px 8px 8px 0;
  border-style: solid;
  border-color: transparent #f0f4fa transparent transparent;
}
.db-msg-content {
  font-size: 16px;
  line-height: 1.7;
}
.db-chat-footer {
  display: flex;
  gap: 12px;
  padding: 20px 32px 24px 32px;
  border-top: 1px solid #e3e8f0;
  background: #fff;
}
.db-chat-footer textarea {
  flex: 1;
  border-radius: 20px;
  border: 1.5px solid #d1d9e6;
  padding: 16px;
  font-size: 16px;
  resize: none;
  min-height: 48px;
  max-height: 140px;
  outline: none;
  background: #f4f7fb;
  scrollbar-width: none;
  -ms-overflow-style: none;
}
.db-chat-footer textarea::-webkit-scrollbar {
  display: none;
}
.db-send-btn {
  border-radius: 20px;
  background: #3578e5;
  border: none;
  font-weight: 700;
  font-size: 17px;
  padding: 0 32px;
  height: 48px;
  color: #fff;
  box-shadow: 0 2px 8px 0 rgba(53,120,229,0.08);
  transition: background 0.18s;
}
.db-send-btn:hover {
  background: #2256b9;
}
@media (max-width: 600px) {
  .db-chat-window {
    max-width: 100vw;
    min-height: 100vh;
    border-radius: 0;
    height: 100vh;
  }
  .db-chat-main {
    padding: 12px 4px;
  }
  .db-chat-footer {
    padding: 12px 8px;
  }
}

/* 添加打字动画 */
.db-msg-bubble.typing::after {
  content: '...';
  animation: typing 1.5s infinite;
}

@keyframes typing {
  0% { content: '.'; }
  33% { content: '..'; }
  66% { content: '...'; }
}

/* 流式消息样式 */
.db-msg-row.ai .db-msg-bubble.streaming {
  background: #e6f0fd;
  border-left: 3px solid #3578e5;
}
</style>
